class Solution(object):
    def totalStrength(self, strength):
        prefix = strength.copy()
        n = len(strength)
        for i in range(n - 2, -1, -1):
            prefix[i] += prefix[i + 1]
        w_prefix = prefix.copy()
        for i in range(n - 2, -1, -1):
            w_prefix[i] += w_prefix[i + 1]
        base = 10 ** 9 + 7
        ans = 0
        st = []
        now_val = 0
        now_min_val = 0
        for index, val in enumerate(strength):
            now_min_val += val
            now_count = 1
            now_index = index
            while st and st[-1][0] >= val:
                x, count = st.pop()
                now_min_val -= count * x
                now_min_val += count * val
                now_count += count
                t_sum = w_prefix[now_index - count] - w_prefix[now_index]
                t_sum -= prefix[now_index] * count
                if now_index != index:
                    t_sum += count * (prefix[now_index] - prefix[index])
                now_index -= count
                now_val = (now_val - (x - val) * t_sum) % base
            st.append([val, now_count])
            now_val = (now_val + now_min_val * val) % base
            ans = (ans + now_val) % base
        return ans


data = Solution()
strength = [1, 3, 1, 2]
print(data.totalStrength(strength))
